#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source $DIR/../../lib/shell/env.sh
source $DIR/network_bandwidth_direct.sh

function server_kill() {
    server_down="kill -9 \`pidof iperf3\` &>/dev/null"
    $ESSH $lts_ip $server_down || return 1
    return 0
}

function server_run() {
    echo "start server listen"
    server_kill
    server_cmd="iperf3 -sD"
    $ESSH $lts_ip $server_cmd &
    if [ $? -eq 0 ]; then
        echo "server listen success"
        sleep 3
        return 0
    else
        echo "server listen failed"
        return 1
    fi
}

function random_test_client_run() {
    echo "start client connect"

    round=$(echo $IPERF3_RUNTIME/10 | bc)
    min=1
    max=64
    range=$(($max-$min+1))

    for (( i=0; i<$round; i++ ));do
        random_size=$(($RANDOM % $range + $min))
        random_size=${random_size}K

        client_cmd="iperf3 -t 10 -i $IPERF3_INTERVAL -P $IPERF3_PROCESS_NUM -f g -c $lts_ip -l $random_size -B $sut_ip"
        run_cmd "$client_cmd" > $IPERF3_LOG &
        [ $? -eq 0 ] || { echo "client connect failed"; return 1; }

        wait $!

        bandwidth_check_results || return 1
    done

    return 0
}

function random_test(){
    check_cmd "iperf3"

    IPERF3_LOG=network_random_log.iperf3
    [ -z "$LTS_IPADDRESS" ] && { echo "Error: LTS IP are required, but none are given";exit 1; }
    lts_ip=$(echo $LTS_IPADDRESS | awk '{print $1}')
    
    server_run
    [ $? -ne 0 ] && return 1

    # clean all iperf3 processes
    if ps -ef|grep iperf3|grep -w $IPERF3_PORT >/dev/null 2>&1;then
        kill -9 `ps -ef|grep iperf3|grep -w $IPERF3_PORT|awk '{print $2}'`
    fi

    [ -n "$INTERFACES" ] || { echo "no interface found";return 1; }
    err=""
    ip_pair=""
    for cur_interface in $INTERFACES; do
        echo $cur_interface
        sut_ip=""
        sut_ip=$(ip addr show $cur_interface | grep -w 'inet' | awk '{print $2}' | awk -F'/' '{print $1}')
        [ -n "$sut_ip" ] || continue

        ping -I $sut_ip $lts_ip -w5 >/dev/null 2>&1 || continue

        ip_pair="pingable ip pair $sut_ip $lts_ip"
        echo $ip_pair

        random_test_client_run || { err='error'; break; }
    done

    if test -f "$IPERF3_LOG"; then
        rm -rf $IPERF3_LOG
    fi

    server_kill || return 1

    [ -n "$ip_pair" ] || {
        echo -e "no valid ip pair for bare devices, please check if your devices are bonded";
        return 1; 
    }

    [ -n "$err" ] && return 1

    return 0
}


# # # # # # # # main # # # # # # # #
trap "bash ../../../utils/sshconf.sh restore" EXIT
bash ../../../utils/sshconf.sh setup
stress_network_env 5 $RUNTIME
random_test && test_pass || test_fail